package com.itheima.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.*;
import com.itheima.pojo.threadlocal.AuthThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * @author ChenJunJie
 * @date 2022/6/12 15:34
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, String> strRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");

        if (token==null){
            throw new UnAuthorizedException(Code.UNAUTHORIZED, "用户未登录");
        }

        boolean b = JwtUtils.verifyToken(token);

        if (!b){
            throw new UnAuthorizedException(Code.UNAUTHORIZED, "token已失效");
        }

        Claims claims = JwtUtils.getClaims(token);

        if (CollectionUtils.isEmpty(claims)){
            throw new UnAuthorizedException(Code.UNAUTHORIZED, "token内容异常");
        }

        Object userName = claims.get("userName");
        if (StrUtil.isEmpty(userName.toString())){
            throw new UnAuthorizedException(Code.UNAUTHORIZED, "token内容异常");
        }

        AuthThreadLocal.setAuth(userName.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthThreadLocal.remove();
    }
}
